'use client';

import type { IDifference } from '@/interfaces';
import { createRole } from '@/services/api';
import { useMutation } from '@tanstack/react-query';
import { type ChangeEvent, type FormEvent, useEffect, useState } from 'react';
import useToast from '@/hooks/useToast';
import diff from 'microdiff';
import { clearFormData, getDiffData } from '@/lib/tool';
import Box from '@/app/[locale]/admin/common/box';
import Spinner from '@/app/[locale]/component/spinner/spinner';
import { useRouter } from 'next/navigation';
import type { PrefixedTTranslatedFields } from '@/lib/dictionaries';

export default function CreatePermissionAdminPage({
  source,
  translatedFields,
}: {
  source?: any;
  translatedFields: PrefixedTTranslatedFields<'permissionAdminPage'>;
}) {
  const [form, setForm] = useState({
    name: '',
  });
  const [differenceData, setDifferenceData] = useState<IDifference[]>([]);
  const { show } = useToast();
  const router = useRouter();
  const [isDisabledSave, setIsDisabledSave] = useState(true);

  const createRoleMutation = useMutation(createRole);

  useEffect(() => {
    const diffData = diff(
      {
        name: '',
      },
      form,
    );
    setDifferenceData(diffData);
    setIsDisabledSave(diffData.length === 0);
  }, [form]);

  async function onSubmit(e: FormEvent<HTMLFormElement>) {
    try {
      e.preventDefault();
      e.stopPropagation();

      checkForm();

      const data: any = getDiffData(differenceData);
      await createRoleMutation.mutateAsync({
        data,
      });

      show({
        type: 'SUCCESS',
        message: translatedFields.operate.saveCompleted,
      });

      setTimeout(() => {
        show({
          type: 'PRIMARY',
          message: translatedFields.operate.refreshPending,
        });
      }, 1000);

      setTimeout(() => {
        router.back();
      }, 1500);
    } catch (e) {
      createRoleMutation.reset();
      show({
        type: 'DANGER',
        message: e,
      });
    } finally {
      setForm(clearFormData(form));
      setDifferenceData([]);
    }
  }

  function checkForm() {
    const { name } = form;

    if (!name) {
      throw translatedFields.tip.requiredPermissionName;
    } else if (
      /[\u4e00-\u9fa5]/.test(name) ||
      /\s/.test(name) ||
      !name.includes('/')
    ) {
      throw translatedFields.tip.invalidPermissionName;
    }
  }

  function onChange(e: ChangeEvent<HTMLInputElement>) {
    const name = e.target.name;
    const value = e.target.value;
    setForm({ ...form, [name]: value });
  }

  return (
    <Box>
      <div className="card">
        <div className="card-body">
          <form onSubmit={onSubmit} className="vstack gap-4">
            <div>
              <label className="form-label">
                {translatedFields.properties.name}
              </label>
              <input
                type="text"
                name="name"
                value={form.name}
                onChange={onChange}
                className="form-control"
                aria-describedby="name"
                placeholder={translatedFields.tip.permissionNamePlaceholder}
              />
            </div>

            <button
              type="submit"
              disabled={createRoleMutation.isLoading || isDisabledSave}
              className="btn btn-primary col col-lg-2 mt-4"
            >
              {createRoleMutation.isLoading && <Spinner classs="me-2" />}
              {translatedFields.operate.save}
            </button>
          </form>
        </div>
      </div>
    </Box>
  );
}
